package divider

import (
	"image"
	"image/color"

	"gioui.org/layout"
	"gioui.org/op/clip"
	"gioui.org/op/paint"
	"gioui.org/unit"
	"gioui.org/widget/material"
)

// WithAlpha returns the input color with the new alpha value.
func WithAlpha(c color.NRGBA, a uint8) color.NRGBA {
	return color.NRGBA{
		R: c.R,
		G: c.G,
		B: c.B,
		A: a,
	}
}

// DividerStyle defines the presentation of a material divider, as specified
// here: https://material.io/components/dividers
type DividerStyle struct {
	Thickness unit.Dp
	Fill      color.NRGBA
	layout.Inset

	Subheading      material.LabelStyle
	SubheadingInset layout.Inset
}

func (d DividerStyle) Layout(gtx layout.Context) layout.Dimensions {
	if gtx.Constraints.Min.X == 0 {
		return layout.Dimensions{}
	}
	return layout.Flex{Axis: layout.Vertical}.Layout(gtx,
		layout.Rigid(func(gtx layout.Context) layout.Dimensions {
			return d.Inset.Layout(gtx, func(gtx layout.Context) layout.Dimensions {
				weight := gtx.Dp(d.Thickness)
				line := image.Rectangle{Max: image.Pt(gtx.Constraints.Min.X, weight)}
				paint.FillShape(gtx.Ops, d.Fill, clip.Rect(line).Op())
				return layout.Dimensions{Size: line.Max}
			})
		}),
		layout.Rigid(func(gtx layout.Context) layout.Dimensions {
			if d.Subheading == (material.LabelStyle{}) {
				return layout.Dimensions{}
			}
			return d.SubheadingInset.Layout(gtx, d.Subheading.Layout)
		}),
	)
}

// Divider creates a simple full-bleed divider.
func Divider(th *material.Theme) DividerStyle {
	return DividerStyle{
		Thickness: unit.Dp(1),
		Fill:      WithAlpha(th.Fg, 0x60),
		Inset: layout.Inset{
			Top:    unit.Dp(8),
			Bottom: unit.Dp(8),
		},
	}
}
